package com.xiaoshou.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.stereotype.Controller;

import com.xiaoshou.luceneutil.SearcherFile;
import com.xiaoshou.pojo.Answers;
import com.xiaoshou.pojo.Question;
import com.xiaoshou.pojo.QuestionFilesRel;
import com.xiaoshou.pojo.Questiontype;
import com.xiaoshou.pojo.User;

@Controller
@Results({
		@Result(name = "searchResult", location = "result.jsp", type = "dispatcher"),
		@Result(name = "saveQuestionSuccess", location = "transMain.action", type = "redirectAction"),
		/*
		 * @Result(name = "toAddQuestionForUser", location =
		 * "addQuestionWithUser.action", type = "redirectAction"),
		 */
		@Result(name = "toAddQuestionPage", location = "askquestion.jsp", type = "dispatcher", params = {
				"questiontypesList", "${questiontypesList}" }),
		@Result(name = "transMainPage", location = "index.action", type = "redirectAction"),
		@Result(name = "toQuestionPage", location = "questionpage.jsp", type = "dispatcher"),
		@Result(name = "toEditQuestion", location = "editquestion.jsp", type = "dispatcher"),
		@Result(name = "updateSuccess", location = "oneQuestion.action", type = "redirectAction", params = {
				"questionId", "${questionId}" }),
		@Result(name = "deleteSuccess", location = "index.action", type = "redirectAction") })
public class QuestionAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	public final static String indexDirForQuestion = "F:\\工作相关索引\\销售索引";
	private List<Document> documentList;
	private String searchQuestion;
	private List<Question> questionsList;
	private List<Questiontype> questiontypesList;

	private User user;
	private Question question;
	private String questionname;
	private String questionId;
	private double time;
	private String questiontypeId;

	/*
	 * 关于分页的一些数据
	 */
	private List<String> pagenum;
	private int startindex;
	private int endindex;
	private int nowPage;
	private int maxPage;
	private int totalcount;

	@Override
	public String execute() throws Exception {

		return null;
	}

	@Action("deleteQuestionById")
	public String deleteQuestionById() {
		question = getQuestionService().getQuestionDao().findById(questionId);
		// 刪除問題的答案
		List<Answers> list = question.getAnswerses();
		if (list != null) {
			for (Answers answers : list) {
				getAnswersService().deleteAnswerById(answers.getId());
			}
		}
		question.getQuestionFilesRels();
		// 删除问题中的文件,及删除上传文件夹中文件
		List<QuestionFilesRel> fileL = question.getQuestionFilesRels();
		System.out.println(fileL.size());
		if (fileL != null) {
			for (QuestionFilesRel filesQuestionRel : fileL) {
				// 删除文件夹中的文件
				// filesQuestionRel.getFiles().getFileurl();
				getFilesService().delFileInTomcat(filesQuestionRel);
				// 删除库中的数据,关系表及有关表
				getFilesService().delFilesOfQuestion(
						filesQuestionRel.getFiles());
			}
		}

		// 删问题更新索引
		getQuestionService().deleteQuestionById(questionId);
		return "deleteSuccess";
	}

	@Action("updateQuestion")
	public String updateQuestion() {
		getQuestionService().updateQuestion(question,questiontypeId);
		
		questionId = question.getId();
		return "updateSuccess";
	}

	@Action("editQuestion")
	public String editQuestion() {
		user = (User) getFromSession("user");
		question = getQuestionService().getQuestionDao().findById(questionId);
		questiontypesList = getQuestionTypeService().findAllQuestionList();
		return "toEditQuestion";
	}

	@Action("oneQuestion")
	public String getOneQuestion() {
		user = (User) getFromSession("user");
		question = getQuestionService().getQuestionDao().findById(questionId);
		return "toQuestionPage";
	}

	@Action("transMain")
	public String transMainPage() {

		return "transMainPage";
	}

	@Action("saveQuestion")
	public String saveQuestion() {
		User user = (User) getFromSession("user");

		getQuestionService().saveQuestion(questionname, questiontypeId, user);
		return "saveQuestionSuccess";

	}

	@Action("addQuestionWithUser")
	public String askQuestionWithUser() {
		questiontypesList = getQuestionTypeService().getQuestionTypeDao()
				.findAll();
		System.out.println("type长度为：" + questiontypesList.size());
		return "toAddQuestionPage";
	}

	@Action("addquestion")
	public String toAddQuestionPage() {
		user = (User) getFromSession("user");
		if (user != null) {
			try {
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setContentType("application/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print("true".toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		} else {// 往前台刷提示，
			try {
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setContentType("application/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print("false".toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	@Action("searchQuestion")
	public String searchQuestion() {
		/*
		 * 搜索
		 */
		long starttime = new Date().getTime();
		pagenum = new ArrayList<String>();
		questionsList = new ArrayList<Question>();
		// fileTypesList = getFiletypeService().getFileTypeDao().findAll();
		try {
			if (!"".equals(searchQuestion.trim())) {
				IndexReader reader = DirectoryReader.open(FSDirectory
						.open(new File(indexDirForQuestion)));// 打开索引
				IndexSearcher searcher = new IndexSearcher(reader);
				totalcount = SearcherFile.getsearchSize(searcher,
						searchQuestion);
				if (totalcount <= 10) {
					pagenum.add("1");
					maxPage = 1;
				} else if (totalcount % 10 != 0) {// 总数不恰好为页数的倍数
					maxPage = totalcount / 10 + 1;
					System.out.println(maxPage % 10);
					if (maxPage < 7) {
						for (int i = 1; i < maxPage + 1; i++) {
							pagenum.add(String.valueOf(i));
						}
					} else {
						if (nowPage < 4) {
							for (int i = 1; i < 7; i++) {
								pagenum.add(String.valueOf(i));
							}
						} else if (nowPage >= (maxPage - 3)) {
							for (int i = (maxPage - 6); i < maxPage; i++) {
								pagenum.add(String.valueOf(i + 1));
							}
						} else {
							pagenum.add(String.valueOf(nowPage - 1));
							pagenum.add(String.valueOf(nowPage));
							pagenum.add(String.valueOf(nowPage + 1));
							pagenum.add(String.valueOf(nowPage + 2));
							pagenum.add(String.valueOf(nowPage + 3));
							pagenum.add(String.valueOf(nowPage + 4));
						}
					}
				} else if (totalcount % 10 == 0) {
					maxPage = totalcount / 10;
					for (int i = 1; i < maxPage + 1; i++) {
						pagenum.add(String.valueOf(i));
					}
				}
				if (nowPage != 0 && (nowPage + 1) < (maxPage)) {
					startindex = nowPage * 10;
					endindex = startindex + 9;
					documentList = SearcherFile.search(searcher,
							searchQuestion, startindex, endindex);// 去搜索
				} else if (nowPage != 0 && (nowPage + 1) == maxPage) {
					startindex = nowPage * 10;
					endindex = totalcount;
					documentList = SearcherFile.search(searcher,
							searchQuestion, startindex, endindex);// 去搜索
				} else if (nowPage == 0) {
					startindex = nowPage * 10;
					endindex = startindex + 9;
					documentList = SearcherFile.search(searcher,
							searchQuestion, startindex, endindex);
				}
				if (documentList != null) {

					System.out.println(documentList.size() + "\t\t长度");
					for (Document d : documentList) {
						String id = d.getField("id").stringValue();
						Question q = getQuestionService().getQuestionDao()
								.findById(id);
						if (!questionsList.contains(q)) {
							questionsList.add(q);
						}
					}
					System.out.println("搜索结果有" + questionsList.size() + "条");
				} else {
					questionsList = null;
				}
				reader.close();
			} else {
				// 全查分页
				// questionsList =
				// getQuestionService().getQuestionDao().findAll();
				findAllByPaging();
			}

		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {

		}
		time = (double) (new Date().getTime() - starttime) / 1000;
		System.out.println("用时：\t"
				+ (double) (new Date().getTime() - starttime) / 1000 + "\t秒");
		return "searchResult";
	}

	/**
	 * 全查分页
	 */
	public void findAllByPaging() {
		totalcount = getQuestionService().getQuestionDao().findAll().size();
		if (nowPage < 0) {
			nowPage = 0;
		} else if (nowPage == 0) {
			questionsList = getQuestionService().findQuestionsListByNowpage(
					nowPage);
		}
		if (totalcount <= 10) {
			pagenum.add("1");
			maxPage = 1;
		} else if (totalcount % 10 != 0) {//
			maxPage = totalcount / 10 + 1; //
			if (maxPage < 7) {
				for (int i = 1; i < maxPage + 1; i++) {
					pagenum.add(String.valueOf(i));
				}
			} else {
				if (nowPage < 4) {
					for (int i = 1; i < 7; i++) {
						pagenum.add(String.valueOf(i));
					}
				} else if (nowPage >= (maxPage - 3)) {
					for (int i = (maxPage - 6); i < maxPage; i++) {
						pagenum.add(String.valueOf(i + 1));
					}
				} else {
					pagenum.add(String.valueOf(nowPage - 1));
					pagenum.add(String.valueOf(nowPage));
					pagenum.add(String.valueOf(nowPage + 1));
					pagenum.add(String.valueOf(nowPage + 2));
					pagenum.add(String.valueOf(nowPage + 3));
					pagenum.add(String.valueOf(nowPage + 4));
				}
			}
		} else if (totalcount % 10 == 0) {//
			maxPage = totalcount / 10; // 页数
			for (int i = 1; i < maxPage + 1; i++) {
				pagenum.add(String.valueOf(i));
			}
		}
		if (nowPage != 0 && (nowPage + 1) < (maxPage)) {
			startindex = nowPage * 10;
			endindex = startindex + 9;
			questionsList = getQuestionService().findQuestionsListByNowpage(
					nowPage);
		} else if (nowPage != 0 && (nowPage + 1) == maxPage) {
			startindex = nowPage * 10;
			endindex = totalcount;
			questionsList = getQuestionService().findQuestionsListByNowpage(
					nowPage);
		}
	}

	// set get方法
	public String getSearchQuestion() {
		return searchQuestion;
	}

	public void setSearchQuestion(String searchQuestion) {
		this.searchQuestion = searchQuestion;
	}

	public List<Question> getQuestionsList() {
		return questionsList;
	}

	public void setQuestionsList(List<Question> questionsList) {
		this.questionsList = questionsList;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getQuestionname() {
		return questionname;
	}

	public void setQuestionname(String questionname) {
		this.questionname = questionname;
	}

	public String getQuestionId() {
		return questionId;
	}

	public void setQuestionId(String questionId) {
		this.questionId = questionId;
	}

	public Question getQuestion() {
		return question;
	}

	public void setQuestion(Question question) {
		this.question = question;
	}

	public int getStartindex() {
		return startindex;
	}

	public void setStartindex(int startindex) {
		this.startindex = startindex;
	}

	public int getEndindex() {
		return endindex;
	}

	public void setEndindex(int endindex) {
		this.endindex = endindex;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getMaxPage() {
		return maxPage;
	}

	public void setMaxPage(int maxPage) {
		this.maxPage = maxPage;
	}

	public int getTotalcount() {
		return totalcount;
	}

	public void setTotalcount(int totalcount) {
		this.totalcount = totalcount;
	}

	public List<String> getPagenum() {
		return pagenum;
	}

	public void setPagenum(List<String> pagenum) {
		this.pagenum = pagenum;
	}

	public double getTime() {
		return time;
	}

	public void setTime(double time) {
		this.time = time;
	}

	public List<Questiontype> getQuestiontypesList() {
		return questiontypesList;
	}

	public void setQuestiontypesList(List<Questiontype> questiontypesList) {
		this.questiontypesList = questiontypesList;
	}

	public String getQuestiontypeId() {
		return questiontypeId;
	}

	public void setQuestiontypeId(String questiontypeId) {
		this.questiontypeId = questiontypeId;
	}

}
